<template>
  <div class="records-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>使用记录</span>
      </div>

      <!-- 筛选表单 -->
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item label="柜子编号">
          <el-input v-model="filterForm.cabinetId" placeholder="请输入柜子编号" />
        </el-form-item>
        <el-form-item label="使用者">
          <el-input v-model="filterForm.userId" placeholder="请输入使用者ID" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">筛选</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 记录表格 -->
      <el-table :data="filteredRecordsForUser" style="width: 100%" v-loading="loading">
        <el-table-column prop="cabinetId" label="柜子编号" width="120" />
        <el-table-column prop="username" label="使用者" width="120" />
        <el-table-column prop="startTime" label="开始时间" width="180">
          <template slot-scope="scope">
            {{ formatDate(scope.row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="结束时间" width="180">
          <template slot-scope="scope">
            {{ formatDate(scope.row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="password" label="使用密码" width="120" />
        <el-table-column prop="duration" label="使用时长" width="120">
          <template slot-scope="scope">
            {{ calculateDuration(scope.row.startTime, scope.row.endTime) }}
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalRecords"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import { mapGetters, mapState } from "vuex";

export default {
  name: "RecordsIndex",
  data() {
    return {
      // 加载状态
      loading: false,
      // 筛选表单数据
      filterForm: {
        dateRange: [],
        cabinetId: "",
        userId: ""
      },
      // 分页相关数据
      currentPage: 1,
      pageSize: 10
    };
  },
  computed: {
    // 从Vuex获取状态
    ...mapGetters(["getCabinetRecords"]),
    ...mapState({
      currentUser: (state) => state.user
    }),
    // 计算总记录数
    totalRecords() {
      return this.filteredRecordsForUser.length;
    },
    // 根据筛选条件过滤记录
    filteredRecordsForUser() {
      // 首先根据当前用户过滤记录
      let records = this.getCabinetRecords.filter(record => record.userId === this.currentUser.id);

      // 根据日期范围筛选
      if (this.filterForm.dateRange && this.filterForm.dateRange.length === 2) {
        const [startDate, endDate] = this.filterForm.dateRange;
        records = records.filter((record) => {
          const recordDate = new Date(record.startTime).toISOString().split("T")[0];
          return recordDate >= startDate && recordDate <= endDate;
        });
      }

      // 根据柜子编号筛选
      if (this.filterForm.cabinetId) {
        records = records.filter((record) =>
          record.cabinetId.toLowerCase().includes(this.filterForm.cabinetId.toLowerCase())
        );
      }

      // 根据用户ID筛选
      if (this.filterForm.userId && this.filterForm.userId !== this.currentUser.id) {
         records = [];
      }

      // 应用分页
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return records.slice(start, end);
    }
  },
  methods: {
    // 格式化日期显示
    formatDate(date) {
      if (!date) return "-";
      return new Date(date).toLocaleString();
    },
    // 计算使用时长
    calculateDuration(startTime, endTime) {
      if (!startTime || !endTime) return "-";
      const start = new Date(startTime);
      const end = new Date(endTime);
      const diff = end - start;
      const hours = Math.floor(diff / (1000 * 60 * 60));
      const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
      return `${hours}小时${minutes}分钟`;
    },
    // 处理筛选操作
    handleFilter() {
      this.currentPage = 1;
    },
    // 重置筛选条件
    resetFilter() {
      this.filterForm = {
        dateRange: [],
        cabinetId: "",
        userId: ""
      };
      this.currentPage = 1;
    },
    // 处理每页显示数量变化
    handleSizeChange(val) {
      this.pageSize = val;
    },
    // 处理页码变化
    handleCurrentChange(val) {
      this.currentPage = val;
    }
  }
};
</script>

<style scoped>
.records-container {
  padding: 20px;
}

.filter-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>
